package com.example.demoapp.activity;

import static com.example.demoapp.bean.util.HttpServer.IP;
import static com.example.demoapp.bean.util.KeyBoardUtils.hintKeyboard;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.demoapp.R;
import com.example.demoapp.bean.Res;
import com.example.demoapp.bean.User;
import com.example.demoapp.bean.util.HttpServer;
import com.example.demoapp.bean.util.JSONParser;
import com.example.demoapp.config.URLs;
import com.example.demoapp.myplayer.Chapter;
import com.example.demoapp.myplayer.ExoPlayerManager;
import com.example.demoapp.myplayer.ExoPlayerService;
import com.example.demoapp.myplayer.LogUtil;
import com.example.demoapp.permission.FloatWindowManager;
import com.example.demoapp.vollley.MySingleton;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.MappingTrackSelector;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.DefaultTimeBar;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.ui.TimeBar;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.cache.CacheDataSourceFactory;
import com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor;
import com.google.android.exoplayer2.upstream.cache.SimpleCache;
import com.google.android.exoplayer2.util.Util;
import com.google.gson.Gson;
import com.jidcoo.android.widget.commentview.CommentView;
import com.jidcoo.android.widget.commentview.callback.OnCommentLoadMoreCallback;
import com.jidcoo.android.widget.commentview.callback.OnItemClickCallback;
import com.jidcoo.android.widget.commentview.callback.OnPullRefreshCallback;
import com.jidcoo.android.widget.commentview.callback.OnReplyLoadMoreCallback;
import com.jidcoo.android.widget.commentview.callback.OnScrollCallback;
import com.jidcoo.android.widget.commentview.defaults.DefaultCommentModel;
import com.jidcoo.android.widget.commentview.defaults.DefaultViewStyleConfigurator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class AudioPlayActivity extends AppCompatActivity implements ExoPlayerService.OnProgressLis {
    //    private SystemBarTintManager tintManager;
    private User user;
    private Context context;
    private String link;
    private String uuid;
    //comment
    private JSONArray data;
    private Gson gson;
    private boolean isReply = false;
    private boolean isChildReply = false;
    private int cp, rp;
    private long fid, pid;
    @BindView(R.id.like)
    ImageButton like;
    @BindView(R.id.collect)
    ImageButton collect;
    @BindView(R.id.share)
    ImageButton share;
    @BindView(R.id.myCommentView)
    CommentView commentView;
    @BindView(R.id.reply_editor)
    EditText editor;
    @BindView(R.id.sendReply)
    Button button;
    @BindView(R.id.iv_music_previous)
    ImageView ivPrevious;
    @BindView(R.id.iv_music_next)
    ImageView ivNext;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.iv_cover)
    ImageView ivCover;
    @BindView(R.id.iv_audio_switch)
    ImageView ivStop;
    @BindView(R.id.exo_progress)
    DefaultTimeBar timeBar;
    private List<Chapter> chapterList = new ArrayList<>();
    @BindView(R.id.btn_show_floating)
    Button btnFloating;
    Unbinder unbinder;
    private ExoPlayerService mService;
    private Intent serviceIntent;
    private ServiceConnection serviceConnection;

    // 用户信息
    private SharedPreferences preferences;
    private DefaultCommentModel.Comment.Reply reply;

    private String likeID;
    private String collectID;
    private boolean clikeLike = false;
    private boolean clikeCollection= false;

    private boolean isLike;
    private boolean isCollect;

    private DefaultCommentModel   defaultCommentModel;

    /**
     * 数据处理
     */
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            data = (JSONArray) msg.obj;
            switch (msg.what) {
                case 1:
                    if (data == null) {
                        commentView.loadFailed(true);
                        return;
                    }
                    defaultCommentModel = JSONParser.getConmment(data, context, user.getToken());
                    commentView.loadComplete(defaultCommentModel);
                    break;
                case 2:
                    if (data == null) {
                        commentView.refreshFailed("请求数据失败，刷新失败", true);
                        return;
                    }
                    commentView.refreshComplete(defaultCommentModel);
                    break;
                case 3:
                    if (data == null) {
                        commentView.loadMoreFailed("请求数据失败，加载更多失败", false);
                        return;
                    }
//                    commentView.loadComplete(JSONParser.getConmment(data));
                    break;
                case 4:
                    if (data == null) {
                        commentView.loadMoreReplyFailed("请求数据失败，加载更多回复失败", false);
                        return;
                    }
//                    commentView.loadComplete(JSONParser.getConmment(data));
                    break;
                case 5:
//                    commentView.addReply(reply, cp);
                    break;
                case 6:
//                    load(URLs.comment_list + "?uuid="+uuid, 2);
                    break;
            }
        }
    };

    /**
     * 网络请求
     * @param code
     */
    private void load( int code) {
        HttpServer.getData(myHandler, code, context,uuid,user.getToken());
    }
    private void send(DefaultCommentModel.Comment.Reply reply, int code) {
        HttpServer.sendData(reply, myHandler, code);
        Map map=new HashMap();
        // 输入参数
        map.put("targetId",uuid);
        map.put("content",reply.reply );
        map.put("targetType","3");
        MySingleton.getInstance(context.getApplicationContext()).getRequestQueue().add(new JsonObjectRequest(URLs.addComment, new JSONObject(map),
                new Response.Listener() {
                    @Override
                    public void onResponse(Object response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());
                            Log.d("jsonObject", jsonObject.toString());
                            int code = jsonObject.getInt("code");
                            if (code == 200){
                                Toast.makeText(context, "评论成功", Toast.LENGTH_SHORT).show();
                                load( 1);
                            }else{
                                Toast.makeText(context, "评论失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context, "评论失败", Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("token", user.getToken());
                return headers;
            }
        });


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initWindow();
        setContentView(R.layout.activity_audio_play);
        context = this;
        ButterKnife.bind(this);// bindview
        unbinder = ButterKnife.bind(this);
        setHintKeyboardView(getWindow().getDecorView());
        //
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            link = URLs.host+"/audios"+extras.getString("LINK");
            uuid = extras.getString("NAME");
            isCollect= (extras.getInt("isCollected")!=0)?true:false;
            isLike = (extras.getInt("isLiked")!=0)?true:false;
        }
        //用户信息
        //获取用户信息
        preferences = getSharedPreferences("LoginPrefs", Context.MODE_PRIVATE);
        user = new Gson().fromJson(preferences.getString("user",""), User.class);
        initWidget();
        //获取点赞收藏状态与ID
        getLikeID();
        getCollectID();
        ivCover.setImageResource(R.drawable.image_01);

        // comment


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar bar = getSupportActionBar();
        if (bar != null) {
            bar.setTitle(" ");
            bar.setDisplayHomeAsUpEnabled(true);
            bar.setHomeButtonEnabled(true);
        }


        //改变图标
        if (isLike) {
            like.setImageResource(R.drawable.ic_like);
        }
        else {
            like.setImageResource(R.drawable.ic_notlike);
        }
        //改变图标
        if (isCollect) {
            collect.setImageResource(R.drawable.ic_iscollect);
        }
        else {
            collect.setImageResource(R.drawable.ic_notcollect);
        }

        // 回复事件
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 隐藏输入法
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(editor.getWindowToken(), 0);
                String userStr = preferences.getString("username", "");
                String data = editor.getText().toString();
                if (!userStr.isEmpty() && !data.isEmpty()) {
//                    if (isReply && isChildReply) {
                    if (true) {
                        //现在需要构建一个回复数据实体类
                        reply = new DefaultCommentModel.Comment.Reply();
                        reply.setKid(fid);
                        reply.setReplierName(userStr);
                        reply.setReply(data);
                        reply.setDate(System.currentTimeMillis());
                        reply.setPid(pid);
                        send(reply,5);
                    } else if (isReply && !isChildReply) {
                        //现在需要构建一个回复数据实体类
                        reply = new DefaultCommentModel.Comment.Reply();
                        reply.setKid(fid);
                        reply.setReplierName(userStr);
                        reply.setReply(data);
                        reply.setDate(System.currentTimeMillis());
                        reply.setPid(0);
                        send(reply,5);
                    } else {
                        send(reply,5);
                    }
                } else {
                    Toast.makeText(context, "内容不能为空", Toast.LENGTH_LONG).show();
                }
            }
        });
        commentView = findViewById(R.id.myCommentView);
        commentView.setViewStyleConfigurator(new DefaultViewStyleConfigurator(this));
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        TextView tv1 = new TextView(this);
        tv1.setText("没有评论哦，快去抢沙发吧~");
        tv1.setTextColor(Color.rgb(0,0,0));
        tv1.setGravity(Gravity.CENTER);
        tv1.setLayoutParams(lp);
        //设置空数据视图
        commentView.setEmptyView(tv1);
        //获取callbackBuilder添加事件回调
        commentView.callbackBuilder()
//                .setOnPullRefreshCallback(new MyOnPullRefreshCallback())
                .setOnCommentLoadMoreCallback(new AudioPlayActivity.MyOnCommentLoadMoreCallback())
                .setOnReplyLoadMoreCallback(new AudioPlayActivity.MyOnReplyLoadMoreCallback())
                .setOnItemClickCallback(new AudioPlayActivity.MyOnItemClickCallback())
                .setOnScrollCallback(new AudioPlayActivity.MyOnScrollCallback())
                //设置完成后必须调用CallbackBuilder的buildCallback()方法，否则设置的回调无效
                .buildCallback();
        load( 1);

        // 点赞
        like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isLike=!isLike;
                clikeLike = true;
                //改变图标
                if (isLike) {
                    like.setImageResource(R.drawable.ic_like);
                }
                else {
                    like.setImageResource(R.drawable.ic_notlike);
                }

            }
        });
        //        收藏
        collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clikeCollection=true;
                isCollect = !isCollect;
                //改变图标
                if (isCollect){
                    collect.setImageResource(R.drawable.ic_iscollect);
                }
                else {
                    collect.setImageResource(R.drawable.ic_notcollect);
                }
            }
        });

        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent share_intent = new Intent();
                share_intent.setAction(Intent.ACTION_SEND);//设置分享行为
                share_intent.setType("text/plain");//设置分享内容的类型
                share_intent.putExtra(Intent.EXTRA_SUBJECT, "share");//添加分享内容标题
                share_intent.putExtra(Intent.EXTRA_TEXT, "share with you:"+"android");//添加分享内容
                //创建分享的Dialog
                share_intent = Intent.createChooser(share_intent, "share");
                startActivity(share_intent);
            }
        });



    }


    @Override
    public void onBackPressed() {
        // 在用户按下返回按钮时设置返回结果并关闭当前 Activity
        Intent resultIntent = new Intent();
        resultIntent.putExtra("isLike", isLike);
        resultIntent.putExtra("isCollect", isCollect);
        setResult(Activity.RESULT_OK, resultIntent);

        if (clikeLike){
            if (likeID!=null){
                changeLike(likeID);
            } else if (isLike){
                addlike();
            }
        }
        if(clikeCollection){
            if (collectID!=null){
                changeCollect(collectID);
            } else if (isCollect){
                addcollect();
            }
        }
        clikeLike = false;
        clikeCollection = false;

        super.onBackPressed();
    }



    @Override
    protected void onResume() {
        super.onResume();
        initWidget();

    }
    @Override
    protected void onPause() {
        super.onPause();

    }
    private MediaSource buildMediaSource(Uri uri) {
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this, "exoplayer-sample");
        return new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
    }

    @TargetApi(19)
    private void initWindow() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//            tintManager = new SystemBarTintManager(this);
//            tintManager.setStatusBarTintColor(getResources().getColor(R.color.tab_top_background));
//            tintManager.setStatusBarTintEnabled(true);
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    private void addcollect(){
        HashMap map = new HashMap();
        map.put("status",1);
        map.put("targetId",uuid);
        map.put("targetType","3");
        MySingleton.getInstance(context.getApplicationContext()).getRequestQueue().add(new JsonObjectRequest(URLs.add_collect, new JSONObject(map),
                new Response.Listener() {
                    @Override
                    public void onResponse(Object response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());
                            int code = jsonObject.getInt("code");
                            if (code == 200) {
                                Toast.makeText(context, "收藏成功", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            Log.i("docuaddcollect出现错误",e.toString());
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context, "addcollect网络出错", Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("token", user.getToken());
                return headers;
            }
        });
    }
    private void addlike(){
        HashMap map = new HashMap();
        map.put("status",1);
        map.put("targetId",uuid);
        map.put("targetType","3");
        MySingleton.getInstance(context.getApplicationContext()).getRequestQueue().add(new JsonObjectRequest(URLs.add_like, new JSONObject(map),
                new Response.Listener() {
                    @Override
                    public void onResponse(Object response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());
                            int code = jsonObject.getInt("code");
                            if (code == 200) {
                                Toast.makeText(context, "点赞成功", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            Log.i("doaddlike出现错误",e.toString());
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context, "addlike网络出错", Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("token", user.getToken());
                return headers;
            }
        });
    }

    private void changeCollect(String ID){
        Uri.Builder builder = Uri.parse(URLs.change_collect_status).buildUpon();
        builder.appendQueryParameter("id",ID);
        builder.appendQueryParameter("status", String.valueOf(isCollect ? 1 : 0));
        String url = builder.build().toString();
        MySingleton.getInstance(context.getApplicationContext()).getRequestQueue().add(new JsonObjectRequest(Request.Method.GET,url, null,
                new Response.Listener() {
                    @Override
                    public void onResponse(Object response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());
                            int code = jsonObject.getInt("code");
                            if (code == 200) {
                                Toast.makeText(context, "changecollect", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            Log.i("dochangeCollect出现错误",e.toString());
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context, "changeCollect网络出错", Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("token", user.getToken());
                return headers;
            }
        });
    }
    private void changeLike(String ID){
        Uri.Builder builder = Uri.parse(URLs.change_like_status).buildUpon();
        builder.appendQueryParameter("id",ID);
        builder.appendQueryParameter("status", String.valueOf(isLike ? 1 : 0));
        String url = builder.build().toString();
        MySingleton.getInstance(context.getApplicationContext()).getRequestQueue().add(new JsonObjectRequest(Request.Method.GET,url, null,
                new Response.Listener() {
                    @Override
                    public void onResponse(Object response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());
                            int code = jsonObject.getInt("code");
                            if (code == 200) {
                                Toast.makeText(context, "changeLike", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            Log.i("dochangeLike出现错误",e.toString());
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context, "changeLike网络出错", Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("token", user.getToken());
                return headers;
            }
        });
    }

    private void getCollectID(){
        HashMap map = new HashMap();
        map.put("targetId",uuid);
        map.put("page",0);
        map.put("pageSize", 50);
        map.put( "createBy",user.getUserId());
        MySingleton.getInstance(context.getApplicationContext()).getRequestQueue().add(new JsonObjectRequest(URLs.collect_list, new JSONObject(map),
                new Response.Listener() {
                    @Override
                    public void onResponse(Object response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());
                            int code = jsonObject.getInt("code");
                            if (code == 200) {
                                JSONObject jdata = jsonObject.getJSONObject("data");
                                // 从JSONObject中获取"data"字段对应的JSONArray
                                JSONArray dataArray = jdata.getJSONArray("records");
                                for (int i = 0; i < dataArray.length(); i++) {
                                    JSONObject dataObject = dataArray.getJSONObject(i);
                                    collectID = dataObject.getString("id");
                                }
                            }
                        } catch (Exception e) {
                            Log.i("dogetCollectID出现错误",e.toString());
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context, "getCollectID网络出错", Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("token", user.getToken());
                return headers;
            }
        });
    }
    private void getLikeID(){
        HashMap map = new HashMap();
        map.put( "targetId",uuid);
        map.put( "page",0);
        map.put( "pageSize", 50);
        map.put( "createBy",user.getUserId());
        MySingleton.getInstance(context.getApplicationContext()).getRequestQueue().add(new JsonObjectRequest(URLs.like_list, new JSONObject(map),
                new Response.Listener() {
                    @Override
                    public void onResponse(Object response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());
                            int code = jsonObject.getInt("code");
                            if (code == 200) {
                                JSONObject jdata = jsonObject.getJSONObject("data");
                                // 从JSONObject中获取"data"字段对应的JSONArray
                                JSONArray dataArray = jdata.getJSONArray("records");
                                for (int i = 0; i < dataArray.length(); i++) {
                                    JSONObject dataObject = dataArray.getJSONObject(i);
                                    likeID = dataObject.getString("id");
                                }
                            }
                        } catch (Exception e) {
                            Log.i("dogetLikeID出现错误",e.toString());
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context, "getLikeID网络出错", Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("token", user.getToken());
                return headers;
            }
        });
    }




    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

//    @Override
//    public void onBackPressed() {
//        /*这是重点*/
//        moveTaskToBack(true);
//    }

    private void initWidget() {
        ExoPlayerManager.getDefault().init(this);
        bindService();
        timeBar.addListener(new TimeBar.OnScrubListener() {
            @Override
            public void onScrubStart(TimeBar timeBar, long position) {
                tvStartTime.setText(Util.getStringForTime(ExoPlayerManager.getDefault().getFormatBuilder()
                        , ExoPlayerManager.getDefault().getFormatter(), position));
            }

            @Override
            public void onScrubMove(TimeBar timeBar, long position) {
                ExoPlayerManager.getDefault().seekToTimeBarPosition(position);
            }

            @Override
            public void onScrubStop(TimeBar timeBar, long position, boolean canceled) {

            }
        });


    }


    @OnClick({R.id.iv_music_previous, R.id.iv_music_next, R.id.iv_audio_switch, R.id.btn_show_floating})
    void onBtnClick(View v) {
        final int id = v.getId();
        if (id == R.id.iv_music_next) {

        } else if (id == R.id.iv_music_previous) {


        } else if (id == R.id.iv_audio_switch) {
            if (!ExoPlayerManager.getDefault().isPaused()) {
                ivStop.setImageResource(R.mipmap.ic_knowledge_audio_suspended);
                ExoPlayerManager.getDefault().pauseRadio();
            } else {
                ivStop.setImageResource(R.mipmap.ic_knowledge_audio_play);
                ExoPlayerManager.getDefault().resumeRadio();
            }
        } else if (id == R.id.btn_show_floating) {
            LogUtil.i();
            if (mService != null) {
                if (FloatWindowManager.getInstance().applyOrShowFloatWindow(this) && !ExoPlayerManager.getDefault().isStoped()) {
                    mService.showWindow();
                    // todo
                } else if (!mService.isWindowDismiss()) {
                    mService.dismissWindow();
                }
            }

        }
    }


    private void bindService() {
        LogUtil.i();
        serviceIntent = new Intent(AudioPlayActivity.this, ExoPlayerService.class);
        if (serviceConnection == null) {
            serviceConnection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    mService = ((ExoPlayerService.MusicBinder) service).getService();
                    mService.setOnProgressLis(AudioPlayActivity.this).initListener();
                    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            /*模仿网络请求*/
                            LogUtil.d("发送请求");
                            ExoPlayerManager.getDefault().startRadio(link);
                        }
                    }, 1000);
                }

                @Override
                public void onServiceDisconnected(ComponentName name) {

                }
            };
            bindService(serviceIntent, serviceConnection, BIND_AUTO_CREATE);
            startService(serviceIntent);
        }
    }

    private void unbindService() {
        if (null != serviceConnection) {
            unbindService(serviceConnection);
            serviceConnection = null;
        }
    }

    @Override
    protected void onDestroy() {
        unbindService();
        unbinder.unbind();
        super.onDestroy();
    }

    @Override
    public void onPositionChanged(long curPositionTime) {
        if (timeBar != null)
            timeBar.setPosition(curPositionTime);
    }

    @Override
    public void onDurationChanged(long durationTime) {
        if (timeBar != null)
            timeBar.setDuration(durationTime);
    }

    @Override
    public void onBufferedPositionChanged(long bufferedPosition) {
        if (timeBar != null)
            timeBar.setBufferedPosition(bufferedPosition);
    }

    @Override
    public void onCurTimeStringChanged(String curTimeString) {
        if (tvStartTime != null) {
            tvStartTime.setText(curTimeString);
        }

    }

    @Override
    public void onDurationTimeStringChanged(String durationTimeString) {
        if (tvEndTime != null) {
            tvEndTime.setText(durationTimeString);
        }

    }

    @Override
    public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
        LogUtil.i("onPlayerStateChanged");
        if (playWhenReady) {
            switch (playbackState) {
                case Player.STATE_READY:
                    LogUtil.d("----time5");
                    ivStop.setImageResource(R.mipmap.ic_knowledge_audio_play);
                    ExoPlayerManager.getDefault().setPaused(false);
                    break;
                case Player.STATE_ENDED:
                    /*如果是节，播放下一首*/
                    LogUtil.i("播放下一首");
                    break;
                default:
                    ivStop.setImageResource(R.mipmap.ic_knowledge_audio_suspended);
                    ExoPlayerManager.getDefault().setPaused(true);
                    break;

            }
        } else {
            ivStop.setImageResource(R.mipmap.ic_knowledge_audio_suspended);
            ExoPlayerManager.getDefault().setPaused(true);
        }
    }

    /**
     * 设置点击软键盘之外区域，软键盘消失
     *
     * @param view
     */
    public void setHintKeyboardView(View view) {
        if (!(view instanceof EditText)) {
            view.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    hintKeyboard((Activity) context);
                    editor.clearFocus();
                    return false;
                }
            });
        }
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View innerView = ((ViewGroup) view).getChildAt(i);
                setHintKeyboardView(innerView);
            }
        }
    }

    // 回调类

    /**
     * 下拉刷新回调类
     */
    class MyOnPullRefreshCallback implements OnPullRefreshCallback {

        @Override
        public void refreshing() {
//            load(IP + "?uuid="+uuid, 2);
        }

        @Override
        public void complete() {
            //加载完成后的操作
            Toast.makeText(AudioPlayActivity.this, "刷新成功", Toast.LENGTH_LONG).show();

        }

        @Override
        public void failure(String msg) {
            if (msg != null)
                Toast.makeText(AudioPlayActivity.this, msg, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 上拉加载更多回调类
     */
    class MyOnCommentLoadMoreCallback implements OnCommentLoadMoreCallback {

        @Override
        public void loading(int currentPage, int willLoadPage, boolean isLoadedAllPages) {
            if (!isLoadedAllPages) {
//                load(IP + "?uuid="+uuid, 2);;
            }
        }

        @Override
        public void complete() {
            //加载完成后的操作
        }

        @Override
        public void failure(String msg) {
            if (msg != null)
                Toast.makeText(AudioPlayActivity.this, msg, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 回复加载更多回调类
     */
    class MyOnReplyLoadMoreCallback implements OnReplyLoadMoreCallback<DefaultCommentModel.Comment.Reply> {

        @Override
        public void loading(DefaultCommentModel.Comment.Reply reply, int willLoadPage) {
            //在默认回复数据模型中，kid作为父级索引
            //为了扩展性，把对应的具体模型传了出来，可根据具体需求具体使用
//            load(IP + "/api?do=gr&kid=" + reply.getKid() + "&currentPage=" + willLoadPage, 4);
        }

        @Override
        public void complete() {
            //加载完成后的操作
        }

        @Override
        public void failure(String msg) {
            if (msg != null)
                Toast.makeText(AudioPlayActivity.this, msg, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 点击事件回调
     */
    class MyOnItemClickCallback implements OnItemClickCallback<DefaultCommentModel.Comment, DefaultCommentModel.Comment.Reply> {

        @Override
        public void commentItemOnClick(int position, DefaultCommentModel.Comment comment, View view) {
            isReply = true;
            cp = position;
            isChildReply = false;
            fid = comment.getFid();
            editor.setText("");
            editor.setHint("回复@" + comment.getPosterName() + ":");
        }

        @Override
        public void replyItemOnClick(int c_position, int r_position, DefaultCommentModel.Comment.Reply reply, View view) {
            isReply = true;
            cp = c_position;
            rp = r_position;
            isChildReply = true;
            fid = reply.getKid();
            pid = reply.getId();
            editor.setText("");
            editor.setHint("回复@" + reply.getReplierName() + ":");
        }
    }

    class MyOnScrollCallback implements OnScrollCallback {

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//            isReply = false;
//            if (editor.getText().toString().length() > 0) {
//                editor.setText("");
//            }
//            editor.setHint("发表你的评论吧~");
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        @Override
        public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

        }
    }
    
}


